#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QStringListModel>
#include <QStringList>
#include <QFileDialog>
#include <QSettings>
#include <QMessageBox>
#include <QDateTime>
#include <QSql>
#include <QSqlQuery>
#include <QSqlError>
#include <QSqlDatabase>
#include <QSqlTableModel>
#include <QClipboard>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    setAcceptDrops(true);
    m_filesModel = new QStringListModel(this);
    ui->fileslistView->setModel(m_filesModel);

    m_tableModel = new QStringListModel(this);
    ui->tablelistView->setModel(m_tableModel);
    // 设置右键菜单
    ui->tablelistView->setContextMenuPolicy(Qt::CustomContextMenu);
    QObject::connect(ui->tablelistView, &QListView::customContextMenuRequested, [&](const QPoint &pos) {
        QMenu menu;
        // 复制动作
        QAction* copyAction = menu.addAction("Copy");
        // 处理
        QObject::connect(copyAction, &QAction::triggered, [&]() {
            QClipboard *clipboard = QApplication::clipboard();
            QModelIndex index =ui->tablelistView->indexAt(pos);
            clipboard->setText(m_tableModel->data(index, Qt::DisplayRole).toString());
        });
        // 可以添加其他菜单
        menu.exec(QCursor::pos());
    });

    m_dbModel = new QStringListModel(this);
    ui->dblistView->setModel(m_dbModel);
    ui->dblistView->setSelectionMode(QAbstractItemView::SingleSelection);
    QObject::connect(ui->dblistView, &QListView::clicked, this, [this](const QModelIndex &index) {
        QSqlDatabase db;
        db = QSqlDatabase::addDatabase("QSQLITE");
        QString selectedString = m_dbModel->data(index, Qt::DisplayRole).toString();
        db.setDatabaseName(selectedString);
        bool ok = db.open();
        if(ok) {
            QSqlQuery query;
            QString cmd = QString("SELECT name FROM sqlite_master WHERE type='table';");
            query.prepare(cmd);
            if (!query.exec()) {
                QMessageBox::information(this, QStringLiteral("错误"), QStringLiteral("删除表失败：%1").arg(query.lastError().text()));
                db.close();
                return;
            }

            QStringList list;
            while (query.next()) {
                list << query.value(0).toString();
            }
            m_tableModel->setStringList(list);
            db.close();
        }
    });

    QPixmap pixmap(":/right.png");
    ui->labelRight->setPixmap(pixmap.scaled(ui->labelRight->size()));
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::dragEnterEvent(QDragEnterEvent *event) {
    if (event->mimeData()->hasUrls()) {
        event->acceptProposedAction();
    }
}

void MainWindow::dropEvent(QDropEvent *event) {
    const QList<QUrl> urls = event->mimeData()->urls();
    QStringList originData = m_filesModel->stringList();
    QStringList data;
    data.clear();
    for (const QUrl &url : urls) {
        qDebug() << "Dropped file:" << url.toLocalFile();
        if(!originData.contains(url.toLocalFile()))
            data << url.toLocalFile();
    }
    originData = originData + data;
    m_filesModel->setStringList(originData);
}

QString getLastOpenDir() {
    QSettings settings("MySoftware", "StockAnalysis");
    return settings.value("lastOpenDir").toString();
}

void setLastOpenDir(const QString& dir) {
    QSettings settings("MySoftware", "StockAnalysis");
    settings.setValue("lastOpenDir", dir);
}

void MainWindow::on_pushButton_clicked()
{
    m_filesModel->setStringList(QStringList());
}


void MainWindow::on_pushButton_3_clicked()
{
    QFileDialog dialog;
    dialog.setFileMode(QFileDialog::ExistingFiles);
    QString dir = getLastOpenDir();
    dialog.setDirectory(dir);
    if (dialog.exec() == QDialog::Accepted) {
        QStringList filesList = dialog.selectedFiles();
        if(filesList.isEmpty())
            return;

        QFileInfo info(filesList.value(0));
        setLastOpenDir(info.absolutePath());

        QStringList originData = m_filesModel->stringList();
        QStringList data;
        data.clear();
        for (const auto &filePath : filesList) {
            if(!originData.contains(filePath))
                data << filePath;
        }

        originData = originData + data;
        m_filesModel->setStringList(originData);
    }
}

bool isValidDate(const QString &dateString) {
    return QDateTime::fromString(dateString, "yyyyMMdd").isValid();
}

bool isValidTime(const QString &timeString) {
    return QTime::fromString(timeString, "mm:ss").isValid();
}

void MainWindow::on_pushButton_2_clicked()
{
    m_dbModel->setStringList(QStringList());
    if(m_filesModel->stringList().isEmpty())
        QMessageBox::information(this, QStringLiteral("错误"), QStringLiteral("文件列表不能为空！"));

    auto fileslist = m_filesModel->stringList();
    for(auto& filePath : fileslist) {
        QFile file(filePath);
        if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
            continue;
        QTextStream in(&file);
        bool titleParse = false;
        QSqlDatabase db;
        QString stockDate = "";
        QString stockName = "";
        QString stockCode = "";
        QString dbName = "";
        QString exportDb = "";

        while (!in.atEnd()) {
            QString line = in.readLine();
            line = line.trimmed();
            QVector<QString> list = line.split(QRegExp("\\s+")).toVector();
            if(list.size() < 0)
                continue;

            if(isValidDate(list.value(0)) && list.size() == 3) {
                titleParse = true;
                stockDate = list.value(0);
                stockName = list.value(1);
                stockCode = list.value(2).remove(")").remove("(");
                dbName = stockCode + "_" + stockName;
                exportDb = QApplication::applicationDirPath() + "/" + dbName +".db";
                QFileInfo info(exportDb);

                db = QSqlDatabase::addDatabase("QSQLITE");
                db.setDatabaseName(exportDb);
                bool ok = db.open();
                if(ok) {
                    QSqlQuery query;
                    // 创建表

                    QString cmd = QString("DROP TABLE IF EXISTS ") + QString("%1_%2").arg(stockName, stockDate);
                    query.prepare(cmd);
                    if (!query.exec()) {
                        QMessageBox::information(this, QStringLiteral("错误"), QStringLiteral("删除表失败：%1").arg(query.lastError().text()));
                        db.close();
                        return;
                    }

                    cmd = QString("CREATE TABLE ") + QString("%1_%2").arg(stockName, stockDate) +
                                  "(stockCode INTEGER NOT NULL,  stockName TEXT NOT NULL, stockPrice FLOAT NOT NULL, stockOrderNum INTEGER NOT NULL, stockOrderDirect TEXT, stockTime TEXT NOT NULL)";
                    query.prepare(cmd);
                    if (!query.exec()) {
                        QMessageBox::information(this, QStringLiteral("错误"), QStringLiteral("创建表失败：%1").arg(query.lastError().text()));
                        db.close();
                        return;
                    }
                }
            }

            if(list.size() >= 4 && list.size() <= 5 && isValidTime(list.value(0))) {
                QString stockDirection = "--";
                if(list.size() == 5)
                stockDirection = list.value(4);
                QSqlQuery query;
                QString cmd = QString("INSERT INTO %1 (stockCode, stockName, stockPrice, stockOrderNum, stockOrderDirect, stockTime) VALUES (%2, \"%3\", %4, %5, \"%6\", \"%7\")").arg(stockName + "_" +  stockDate).arg(stockCode.toInt()).arg(stockName).arg(list.value(1).toFloat()).arg(list.value(2).toInt()).arg(stockDirection).arg(list.value(0));
                query.prepare(cmd);
                if (!query.exec()) {
                    QMessageBox::information(this, QStringLiteral("错误"), QStringLiteral("插入数据失败：%1").arg(query.lastError().text()));
                    db.close();
                    return;
                }
            }
        }
        if(!titleParse) {
            QMessageBox::information(this, QStringLiteral("错误"), QStringLiteral("不支持的文件！"));
            db.close();
            return;
        }

        file.close();

        QStringList originData = m_dbModel->stringList();
        if(!originData.contains(exportDb))
            originData << exportDb;
        m_dbModel->setStringList(originData);

        db.close();
    }
}


void MainWindow::on_pushButton_4_clicked()
{
    QModelIndexList dbIndexes = ui->dblistView->selectionModel()->selectedIndexes();
    if(dbIndexes.size() == 0) {
        QMessageBox::information(this, QStringLiteral("错误"), QStringLiteral("请选择数据库！"));
        return;
    }
    QString selectedDB = m_dbModel->data(dbIndexes.value(0), Qt::DisplayRole).toString();

    QSqlDatabase db;
    db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName(selectedDB);
    bool ok = db.open();
    if(ok) {
        QSqlQueryModel *model = new QSqlQueryModel(ui->table);
        // while(model->canFetchMore()) {
        //     model->fetchMore();
        // }
        model->setQuery(QSqlQuery(ui->textEdit->toPlainText(), db));
        ui->table->setModel(model);

        if (model->lastError().type() != QSqlError::NoError)
            QMessageBox::information(this, QStringLiteral("错误"), QStringLiteral("查询错误：%1").arg(model->lastError().text()));

        db.close();
    }
}

